﻿using PIMS.Base;
using PIMS.DBModel;
using PIMS.Interface;
using PIMS.WorkPlugin.ORM;
using PIMS.WorkPlugin.Util;
using PIMS.XmlModel;
using PIMS_Interface.Interface;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace PIMS.WorkPlugin
{
    public class KE23015_WeightHandle : IPLCSignalHandle, IDisposable
    {
        private IDebugMsg debug = null;
        ICommunication plc = null;
        ILog4net log = null;
        int plcIndex = -1;
        TimeSpan s1;
        string sWeight = "";
        PIMSConfigX config = null;
        bool heartBit = false;
        string oldMsg = "";
        string plant = "";

        private PLCSignalHandlePlus x1 = null;
        private BackgroundWorker bgw1 = null;

        CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
        bool alive = false;

        #region Packer实现日志分组功能
        private void DebugMsg(string Msg, InfoLevel level = InfoLevel.info)
        {
            debug.DebugMsg(Msg, LogGroup.weight, level);
        }

        private void LogInfo(string message)
        {
            log.Info(message, LogGroup.weight, plcIndex + 1);
        }

        private void LogError(string message)
        {
            log.Error(message, LogGroup.weight, plcIndex + 1);
        }

        private void LogError(string message, Exception ex)
        {
            log.Error(message, LogGroup.weight, plcIndex + 1, ex);
        }
        #endregion

        /// <summary>
        /// PIMS主程序自动反射加载
        /// </summary>
        /// <param name="plc"></param>
        /// <param name="plcIndex"></param>
        /// <param name="debugMsg"></param>
        /// <param name="log4net"></param>
        public void Init(ICommunication plc, int plcIndex, IDebugMsg debugMsg, ILog4net log4net, PIMSConfigX pimsConfig)
        {
            this.plc = plc;
            this.plcIndex = plcIndex;
            this.debug = debugMsg;
            this.log = log4net;
            this.config = pimsConfig;

            this.plant = pimsConfig.GetAppValueByKey("plant");

            (new System.Threading.Tasks.Task(Thread_CommicationPLC, cancelTokenSource.Token)).Start();

            DebugMsg(String.Format("KE24004_WeightHandle{0} 挂载成功！", this.plcIndex));
            LogInfo(String.Format("KE24004_WeightHandle{0} 挂载成功！", this.plcIndex));
        }

        public void Dispose()
        {
            try
            {
                cancelTokenSource.Cancel();
            }
            catch
            {
            }
        }

        private void Thread_CommicationPLC()
        {
            while (!cancelTokenSource.IsCancellationRequested)
            {
                try
                {
                    if (plc.IsConnected)
                    {
                        if (!alive)
                        {
                            alive = true;
                            this.DebugMsg(plc.GetDeviceName() + "连接成功！", InfoLevel.info);
                            this.LogInfo(plc.GetDeviceName() + "连接成功！");
                        }
                        HandleCycle();
                    }
                    else
                    {
                        alive = false;
                        Thread.Sleep(1000);
                        plc.Connect();
                    }
                }
                catch(Exception ex)
                {
                    if (oldMsg != ex.Message)
                    {
                        oldMsg = ex.Message;
                        this.DebugMsg(plc.GetDeviceName() + oldMsg, InfoLevel.error);
                        this.LogError(plc.GetDeviceName() + oldMsg, ex);
                    }
                    plc.DisConnect();
                }
                Thread.Sleep(300);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="plc"></param>
        /// <param name="index"></param>
        public void HandleCycle()
        {
            if (plc.IsConnected)
            {
                if (3 <= s1.Subtract(new TimeSpan(DateTime.Now.Ticks)).Duration().Seconds)
                {
                    s1 = new TimeSpan(DateTime.Now.Ticks);
                    this.heartBit = !this.heartBit;
                    plc.Write<bool>(Weight.PLC心跳, this.heartBit);
                }
            }
        }

    }
}
